package com.jkhan.demo.ioflow;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @ClassName FileWriterTest
 * @Description FileWriterTest
 * @Author hjk
 * @Date 2022/2/15 19:13
 **/
public class FileWriterTest {
    /**
     * 输出操作：如果文件不存在，则创建文件，
     * 若文件存在，FileWriter(file)/FileWriter(file, false) 则覆盖源文件
     * FileWriter(file, true) 则在原有文件基础上追加内容
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) {
        //提供File对象，指明写出的文件
        File file = new File("hello.txt");

        //提供FileWriter对象，用于数据写出
        FileWriter fileWriter = null;

        try {
            fileWriter = new FileWriter(file);

            //写出操作
            fileWriter.write("I have a dream!\n");
            fileWriter.write("you need to have a dream!");

            System.out.println("写出成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //流关闭
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
